package com.cyzy.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.TeaException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AliyunOrcUtil {
    @Value("${aliyun.ocr.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.ocr.accKeySecret}")
    private String accKeySecret;
    @Value("${aliyun.ocr.endpoint}")
    private String endpoint;

    /**
     *
     * <b>description</b> :
     * <p>使用AK&amp;SK初始化账号Client</p>
     * @return Client
     *
     * @throws Exception
     */
    public  com.aliyun.ocr_api20210707.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(accKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.endpoint = endpoint;
        return new com.aliyun.ocr_api20210707.Client(config);
    }

    //    ======================================
    //    驾驶证识别
    public Map<String,Object> recognitionDriversLicense(String imgPath) throws Exception {
        com.aliyun.ocr_api20210707.Client client = this.createClient();
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream =
                com.aliyun.darabonba.stream.Client.readFromFilePath(imgPath);
        com.aliyun.ocr_api20210707.models.RecognizeDrivingLicenseRequest recognizeDrivingLicenseRequest = new com.aliyun.ocr_api20210707.models.RecognizeDrivingLicenseRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        //读取超时
        runtime.readTimeout=10000;
        //连接超时
        runtime.connectTimeout=5000;
        //是否自动重试
        runtime.autoretry=false;

        Map<String,Object> result = new HashMap<>();

        try {
            com.aliyun.ocr_api20210707.models.RecognizeDrivingLicenseResponse resp =
                    client.recognizeDrivingLicenseWithOptions(recognizeDrivingLicenseRequest, runtime);

            JSONObject dataObject = JSON.parseObject(resp.getBody().getData());
            JSONObject data = dataObject.getJSONObject("data").getJSONObject("face");

            //证号
            String licenseNumber = data.getJSONObject("data").getString("licenseNumber");
            //车主
            String name = data.getJSONObject("data").getString("name");
            //使用性质
            String sex = data.getJSONObject("data").getString("sex");
            //车辆识别代号
            String nationality = data.getJSONObject("data").getString("nationality");
            //发动机号码
            String address = data.getJSONObject("data").getString("address");
            //注册日期
            String birthDate = data.getJSONObject("data").getString("birthDate");
            //发证日期
            String initialIssueDate = data.getJSONObject("data").getString("initialIssueDate");
            String approvedType = data.getJSONObject("data").getString("approvedType");
            String validPeriod = data.getJSONObject("data").getString("validPeriod");

            result.put("licenseNumber",licenseNumber);
            result.put("name",name);
            result.put("sex",sex);
            result.put("nationality",nationality);
            result.put("address",address);
            result.put("birthDate",birthDate);
            result.put("initialIssueDate",initialIssueDate);
            result.put("approvedType",approvedType);
            result.put("validPeriod",validPeriod);

            return result;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }


    //    ======================================
    //    行驶证识别
    public Map<String,Object> recognitionPermit(String imgPath) throws Exception {
        com.aliyun.ocr_api20210707.Client client = this.createClient();
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream =
                com.aliyun.darabonba.stream.Client.readFromFilePath(imgPath);
        com.aliyun.ocr_api20210707.models.RecognizeVehicleLicenseRequest recognizeVehicleLicenseRequest = new com.aliyun.ocr_api20210707.models.RecognizeVehicleLicenseRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

        //读取超时
        runtime.readTimeout=10000;
        //连接超时
        runtime.connectTimeout=5000;
        //是否自动重试
        runtime.autoretry=false;

        Map<String,Object> result = new HashMap<>();

        try {
            com.aliyun.ocr_api20210707.models.RecognizeVehicleLicenseResponse resp =
                    client.recognizeVehicleLicenseWithOptions(recognizeVehicleLicenseRequest, runtime);

            JSONObject dataObject = JSON.parseObject(resp.getBody().getData());
            JSONObject data = dataObject.getJSONObject("data").getJSONObject("face");
            //车牌
            String licencePlate = data.getJSONObject("data").getString("licensePlateNumber");
            //车主
            String owner = data.getJSONObject("data").getString("owner");
            //使用性质
            String useNature = data.getJSONObject("data").getString("useNature");
            //车辆识别代号
            String vinCode = data.getJSONObject("data").getString("vinCode");
            //发动机号码
            String engineNumber = data.getJSONObject("data").getString("engineNumber");
            //注册日期
            String registrationDate = data.getJSONObject("data").getString("registrationDate");
            //发证日期
            String issueDate = data.getJSONObject("data").getString("issueDate");

            result.put("licencePlate",licencePlate);
            result.put("owner",owner);
            result.put("useNature",useNature);
            result.put("vinCode",vinCode);
            result.put("engineNumber",engineNumber);
            result.put("registrationDate",registrationDate);
            result.put("issueDate",issueDate);

            return result;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }



    //    ======================================
    //    身份证识别
    public Map<String,Object> recognitionIdNum(String imgPath) throws Exception{
        com.aliyun.ocr_api20210707.Client client = this.createClient();
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream = com.aliyun.darabonba.stream.Client.readFromFilePath(imgPath);
        com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest recognizeIdcardRequest = new com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse resp = client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);
            JSONObject dataObj= JSON.parseObject(resp.body.data);
            JSONObject data=dataObj.getJSONObject("data").getJSONObject("face");
            //姓名
            String name=data.getJSONObject("data").getString("name");
            //性别
            String sex=data.getJSONObject("data").getString("sex");
            //出生年月
            String birthDate=data.getJSONObject("data").getString("birthDate");
            //民族
            String ethnicity=data.getJSONObject("data").getString("ethnicity");
            //地址
            String address=data.getJSONObject("data").getString("address");
            //身份证号码
            String idNumber=data.getJSONObject("data").getString("idNumber");

            //System.out.println(name+"----"+sex+"----"+birthDate+"----"+ethnicity+"----"+address+"----"+idNumber);

            Map<String,Object> map=new HashMap<>();
            map.put("name",name);
            map.put("sex",sex);
            map.put("birthDate",birthDate);
            map.put("ethnicity",ethnicity);
            map.put("address",address);
            map.put("idNumber",idNumber);
            return map;

        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }



    //    ======================================
    //    车牌识别
    public Map<String,Object> recognitionCarNum(String imgPath) throws Exception {
        com.aliyun.ocr_api20210707.Client client = this.createClient();
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        java.io.InputStream bodyStream =
                com.aliyun.darabonba.stream.Client.readFromFilePath(imgPath);
        com.aliyun.ocr_api20210707.models.RecognizeCarNumberRequest recognizeCarNumberRequest = new com.aliyun.ocr_api20210707.models.RecognizeCarNumberRequest()
                .setBody(bodyStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        //读取超时
        runtime.readTimeout=10000;
        //连接超时
        runtime.connectTimeout=5000;
        //是否自动重试
        runtime.autoretry=false;

        Map<String,Object> result = new HashMap<>();

        try {
            com.aliyun.ocr_api20210707.models.RecognizeCarNumberResponse resp =
                    client.recognizeCarNumberWithOptions(recognizeCarNumberRequest, runtime);

            JSONObject dataObject = JSON.parseObject(resp.getBody().getData());
            JSONObject data = dataObject.getJSONObject("data");
            //车牌
            String licencePlate = data.getJSONObject("data").getString("车牌");
            //车辆类型
            String carType = data.getJSONObject("secondary_cls").getString("type_str");
            //相似度
            String carProb = data.getJSONObject("secondary_cls").getString("prob");

            result.put("licencePlate",licencePlate);
            result.put("carType",carType);
            result.put("carProb",carProb);

            return result;
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }

}
